package com.s666.demo.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Arrays;
import java.util.Base64;


public class AesCBC {

		public static String encrypt(String data, String secretKey) throws Exception {
			byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
			byte[] key = Arrays.copyOfRange(keyBytes, 0, 16); // AES-128需要16字节密钥 [[2]][[9]]
			byte[] iv = Arrays.copyOfRange(keyBytes, 16, 32); // CBC模式需要16字节IV [[4]][[7]]

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 使用PKCS5Padding填充 [[4]][[7]]
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
			IvParameterSpec ivSpec = new IvParameterSpec(iv);

			cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
			byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
			return java.util.Base64.getEncoder().encodeToString(encrypted); // Base64编码 [[7]][[10]]
		}

		public static String decrypt(String encryptedData, String secretKey) throws Exception {
			byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
			byte[] key = Arrays.copyOfRange(keyBytes, 0, 16);
			byte[] iv = Arrays.copyOfRange(keyBytes, 16, 32);

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
			IvParameterSpec ivSpec = new IvParameterSpec(iv);

			cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
			byte[] decoded = Base64.getDecoder().decode(encryptedData);
			byte[] decrypted = cipher.doFinal(decoded);
			return new String(decrypted, StandardCharsets.UTF_8);
		}
	}